#include "uscrollbar.h"
#include <QEvent>
#include <QMouseEvent>
#include "ulistwidget.h"
UScrollBar::UScrollBar(QWidget* parent)
    : QWidget(parent)
    , m_pWidget(parent)
{
    setAttribute(Qt::WA_StyledBackground, true);//默认Qwidget类 无法设置颜色
    setStyleSheet(R"(
    UScrollBar{
    background-color:rgba(171, 169, 167, 128);
    border-radius:4px;
    }
    UScrollBar:hover{
    background-color:#B3B0AF;
    }
    )");
    installEventFilter(this);
    hide();
    m_enable = true;
}

void UScrollBar::adjustSize()
{
    int size = static_cast<UListWidget*>(m_pWidget)->boxSize();
    if (size == 0)
        size = 1;
    int length = m_pWidget->height() * m_pWidget->height() / (size * 127);

    m_enable = length < m_pWidget->height();
    resize(8, std::max(40, length));
}


void UScrollBar::show()
{
    if (m_enable)
        QWidget::show();
}

void UScrollBar::move(int x, int y)
{
    if (m_enable)
        QWidget::move(x, y);
}

bool UScrollBar::eventFilter(QObject* obj, QEvent* event)
{
    static bool s_pressed = false;
    static int s_pressedPointY;
    switch (event->type())
    {
    case QEvent::MouseButtonPress:
        if (static_cast<QMouseEvent*>(event)->button() == Qt::LeftButton
            && cursor().shape() == Qt::ArrowCursor) //只能左键按压滑动

            s_pressed = true;
        s_pressedPointY = static_cast<QMouseEvent*>(event)->pos().y();
        break;
    case QEvent::MouseButtonRelease:s_pressed = false;  break;
    case QEvent::MouseMove:
        if (s_pressed)
        {
            int offsetY = static_cast<QMouseEvent*>(event)->pos().y() - s_pressedPointY;
            if (pos().y() + offsetY < 0)move(pos().x(), 0);
            else if (pos().y() + offsetY >= m_pWidget->height() - height())move(pos().x(), m_pWidget->height() - height());
            else move(pos().x(), pos().y() + offsetY);

            emit valueChanged(100. * pos().y() / (m_pWidget->height() - height()));
        }
        break;
    }
    return false;
}

UScrollBar::~UScrollBar()
{}

int UScrollBar::sliderPosition()
{
    return 100. * pos().y() / (m_pWidget->height() - height());
}

void UScrollBar::setSliderPosition(int posY)
{
    if (!m_enable)return;
    if (posY < 0)posY = 0;
    if (posY > 100)posY = 100;
    move(m_pWidget->width() - 8, posY * (m_pWidget->height() - height()) / 100.);
    emit valueChanged(posY);
}
